$(function () {

    // bootstrap-switch加载
    $('[name="headPostType"]').bootstrapSwitch();

    // 加载select2
    $('.select2').select2();

    // 修改两个select的无数据时反馈字符串
    $("#firstPetCategories").select2({
        language: {
            noResults: function (params) {
                return "无数据";
            }
        }
    });
    $("#secondPetCategories").select2({
        language: {
            noResults: function (params) {
                return "无数据";
            }
        }
    });

    // 点击宠物匹配
    $('#petMatch').click(function () {
        // 宠物分类
        $.ajax({
            type: 'GET',
            url: '/firstPetCategories',
            success: function (result) {
                let firstPetCategories = $('#firstPetCategories');
                let secondPetCategories = $('#secondPetCategories');
                // 先清空之前的分类
                firstPetCategories.empty();
                secondPetCategories.empty();
                if (result.statusCode === 200) {
                    // 一级分类
                    selectCreate(firstPetCategories, result.data);
                    // 二级分类
                    selectCreate(secondPetCategories, result.data[0].secondPetCategories)
                } else {
                    selectCreateError(firstPetCategories, result.message);
                }
            }
        });
        // 地址分类数据
        $.ajax({
            type: 'GET',
            url: '/firstAddressCategories',
            success: function (result) {
                let firstAddresses = $('#firstAddresses');
                let secondAddresses = $('#secondAddresses');
                let thirdAddresses = $('#thirdAddresses');
                // 先清空之前的分类
                firstAddresses.empty();
                secondAddresses.empty();
                thirdAddresses.empty();
                if (result.statusCode === 200) {
                    selectCreateForAddress(firstAddresses, result.data); // 一级分类
                    selectCreateForAddress(secondAddresses, result.data[0].secondAddressCategories); // 二级分类
                    selectCreateForAddress(thirdAddresses, result.data[0].secondAddressCategories[0].thirdAddressCategories); // 三级分类
                } else {
                    selectCreateForAddressError(firstAddresses, result.message); // 一级分类显示错误
                }
            }
        });
    });

    // 二级分类
    $('#firstPetCategories').on('change', function () {
        let categoryId = $(this).find('option:selected').val();
        $.ajax({
            type: 'GET',
            url: '/secondPetCategories',
            data: {categoryId: categoryId},
            success: function (result) {
                // 二级分类
                let secondPetCategories = $('#secondPetCategories');
                // 先清空之前的二级分类
                secondPetCategories.empty();
                if (result.statusCode === 200) {
                    selectCreate(secondPetCategories, result.data);
                } else {
                    selectCreateError(secondPetCategories, result.message);
                }
            }
        });
    });

    // 修改三个select的无数据时反馈字符串
    $("#firstAddresses").select2({
        language: {
            noResults: function (params) {
                return "无数据";
            }
        }
    });
    $("#secondAddresses").select2({
        language: {
            noResults: function (params) {
                return "无数据";
            }
        }
    });
    $("#thirdAddresses").select2({
        language: {
            noResults: function (params) {
                return "无数据";
            }
        }
    });

    // 二、三级地址变化
    $('#firstAddresses').on('change', function () {
        let addressId = $(this).find('option:selected').val();
        $.ajax({
            type: 'GET',
            url: '/secondAddressCategories',
            data: {addressId: addressId},
            success: function (result) {
                let secondAddresses = $('#secondAddresses');
                let thirdAddresses = $('#thirdAddresses');
                // 先清空之前的
                secondAddresses.empty();
                thirdAddresses.empty();
                if (result.statusCode === 200) {
                    selectCreateForAddress(secondAddresses, result.data);
                    selectCreateForAddress(thirdAddresses, result.data[0].thirdAddressCategories);
                } else {
                    selectCreateForAddressError(secondAddresses, result.message);
                }
            }
        });
    });

    // 三级地址变化
    $('#secondAddresses').on('change', function () {
        let addressId = $(this).find('option:selected').val();
        $.ajax({
            type: 'GET',
            url: '/thirdAddressCategories',
            data: {addressId: addressId},
            success: function (result) {
                let thirdAddresses = $('#thirdAddresses');
                // 先清空之前的
                thirdAddresses.empty();
                if (result.statusCode === 200) {
                    selectCreateForAddress(thirdAddresses, result.data);
                } else {
                    selectCreateForAddressError(thirdAddresses, result.message);
                }
            }
        });
    });

    // 图片点击打开文件选择框
    $('#headOpenMainImage').click(function () {
        $('#headMainImage').click();
    });
    $('#headMainImageDiv').click(function () {
        $('#headMainImage').click();
    });

    // 主图选择
    $('#headMainImage').on('change', function (e) {
        var mainImage = e.target.files[0]; // 又卡了半天
        if(checkImage(mainImage)){
            var reader = new FileReader(); // 创建FileReader对象
            // 使用FileReader的readAsDataURL方法读取文件内容
            reader.readAsDataURL(mainImage);
            reader.onload = function (e) {
                // 读取成功后，设置img的src为结果中的data URL
                $('#headMainImageDiv').css('display', 'block').find('img').attr('src', e.target.result);
                $('#headOpenMainImage').css('display', 'none');
            };
        }else{
            $('#headMainImageDiv').css('display', 'none');
            $('#headOpenMainImage').css('display', 'block');
        }
    });

    // 查询
    $('#find').click(function () {
        $(this).attr('disabled', true);
        // 图片
        var headMainImage = $('#headMainImage').prop("files")[0];
        if (!checkImage(headMainImage)) {
            $(this).attr('disabled', false);
            return;
        }
        // 表单数据
        var data = new FormData();
        data.append('Image', headMainImage);
        var petCategoryId = $('#secondPetCategories').find('option:selected').val(); // 分类和地址不用判断了，反正String映射不上后端
        var addressCategoryId = $('#thirdAddresses').find('option:selected').val();
        var postType = ($('#headPostType').bootstrapSwitch('state')) ? '0' : '1';
        data.append('petCategoryId', petCategoryId);
        data.append('addressCategoryId', addressCategoryId);
        data.append('postType', postType);
        // 发送请求
        $.ajax({
            type: 'POST',
            processData: false,  // 注意：让jQuery不要处理数据
            contentType: false,  // 注意：让jQuery不要设置contentType
            url: '/searchImg/match',
            data: data,
            success: function (result) {
                if (result.statusCode === 200) {
                    // 跳转到帖子页面
                    window.location.href = '/searchImg?page=1&image=' + result.data;
                } else {
                    toastr.error(result.message, {timeOut: 3000});
                }
            },
            complete: function (){
                $('#find').attr('disabled', false);
            }
        });
    });

    // 搜索
    $('#searchButton').click(function () {
        let searchInput = $('#searchInput').val();
        searchInput = searchInput.trim();
        console.log(searchInput==='');
        if (searchInput === '') {
            window.location.href = '/index';
        }else{
            window.location.href = '/search?keyword=' + searchInput;
        }
    });

    // 搜索回车监听
    $('#searchInput').keypress(function (e) {
        if(e.which === 13){
            $('#searchButton').click();
        }
    })
});

// 代码简化，petCategories是<select>
function selectCreate(petCategories, data) {
    for (let i = 0; i < data.length; i++) {
        let option = $('<option>');
        if (i === 0) {
            option.attr('selected', 'selected');
        }
        option.attr('value', data[i].categoryId);
        option.text(data[i].categoryName);
        petCategories.append(option);
    }
}

function selectCreateError(petCategories, message) {
    let option = $('<option>');
    option.attr('selected', 'selected');
    option.text(message);
    petCategories.append(option);
}

function selectCreateForAddress(addresses, data) {
    for (let i = 0; i < data.length; i++) {
        let option = $('<option>');
        if (i === 0) {
            option.attr('selected', 'selected');
        }
        option.attr('value', data[i].addressId);
        option.text(data[i].addressName);
        addresses.append(option);
    }
}

function selectCreateForAddressError(addresses, message) {
    let option = $('<option>');
    option.attr('selected', 'selected');
    option.text(message);
    addresses.append(option);
}

function checkImage(image) {
    if (image === undefined) {
        toastr.warning('未选择图片！', '警告', {timeOut: 5000});
        return false;
    } else if (!image.type.startsWith('image/')) {
        toastr.warning('请选择图片类型文件！', '警告', {timeOut: 5000});
        return false;
    } else if (image.size > 3 * 1024 * 1024) {
        toastr.warning('图片最大限制3MB！', '警告', {timeOut: 5000});
        return false;
    }
    return true;
}